<?php
declare(strict_types=1);

namespace LowCode;

use Illuminate\Support\Collection;

class AutoId
{
    private static AutoId $instance;

    protected string $prefix = "uuid";
    protected Collection $ids;

    public function __construct(){
        $this->ids = Collection::make();
    }

    /**
     * @param string|null $prefix
     * @return string
     */
    public static function make(string $prefix = null): string
    {
        if (!isset(self::$instance) || !(self::$instance instanceof self)) {
            self::$instance = new self();
        }
        return self::$instance->getId($prefix);
    }

    protected function getId(string $prefix = null): string
    {
        if ($prefix){
            $this->prefix = $prefix;
        }
        $collect = $this->ids->get($this->prefix, Collection::make());
        if ($collect->isEmpty()){
            $id = 1;
        }else{
            $id = $collect->last()+1;
        }
        $collect->add($id);
        $this->ids->put($this->prefix, $collect);
        return "auto_id_".$this->prefix."_".$id;
    }
}
